<?php

namespace Common\trait;

use Hyperf\DbConnection\Db;
use Hyperf\Support\Filesystem\Filesystem;
use Symfony\Component\Finder\SplFileInfo;

trait UninstallScriptTrait {

    private function deleteMenus(string $name): void
    {
        if (empty($name)) {
            return;
        }
        $grandparentID = Db::table('menu')->where('name', $name)->first(['id']);
        if ($grandparentID) {
            $grandparentID = $grandparentID->id;
            $parentIDs = Db::table('menu')->where('parent_id', $grandparentID)->pluck('id');
            if ($parentIDs) {
                Db::table('menu')->whereIn('parent_id', $parentIDs)->delete();
            }
            Db::table('menu')->where('parent_id', $grandparentID)->delete();
            Db::table('menu')->where('id', $grandparentID)->delete();
        }
    }

    private function deleteLanguages($path): void
    {
        $delete = [];
        $fileSystem = new Filesystem();
        if (!$fileSystem->exists($path . '/../languages/')) {
            return;
        }
        $paths = $fileSystem->directories($path . '/../languages/');
        foreach ($paths as $path) {
            $delete = array_merge($delete, array_map(function(SplFileInfo $o){
                return $o->getFilename();
            }, $fileSystem->files($path)));
        }
        $delete = array_unique($delete);
        $paths = $fileSystem->directories(BASE_PATH . '/storage/languages/');
        foreach ($paths as $path) {
            foreach ($delete as $file) {
                if (file_exists($path . '/' . $file)) {
                    unlink($path . '/' . $file);
                }
            }
        }
    }
}